from django.shortcuts import render,HttpResponse,HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt

from application.models import notebookAndCellPhoneAndPadInfos,notebookAndCellPhoneAndPadInfos,userInfo,projectInfo,projectAndWorkerRelations,projectAndCaseRelations,caseInfo,caseDetail,bugs,uploadImg
import sys,os

def loginPage(request):
    return render(request, "loginPage.html")


def login(request):
    userName = request.POST.get('userName');
    passWord = request.POST.get('password');
    user = userInfo.objects.filter(userName=userName,passWord=passWord,status='1');
    context = {}
    if user.count()>0:
        id = user[0].id
        showName = user[0].showName
        context['id'] = id
        context['showName'] = showName
        request.session['userId'] = id;
        request.session['userName'] = user[0].userName;
        request.session['showName'] = showName;
        request.session['role'] = user[0].role;
        proAndWorker = projectAndWorkerRelations.objects.filter(userId=id)
        projectAndWorkers = []
        if proAndWorker.count()>0:
            for o in proAndWorker:
                info = {}
                info['userId'] = o.userId
                info['projectId'] = o.projectId
                project = projectInfo.objects.filter(id=o.projectId)
                if project.count()>0:
                    info['projectName'] = project[0].projectName;
                projectAndWorkers.append(info)
        context['projectAndWorkers'] = projectAndWorkers
        if user[0].role == '1':
            return render(request, "worker/projectSelect.html", context)
        if user[0].role == '2':
            return HttpResponseRedirect("/projectManagePage/");
    return render(request, "loginPage.html");


def registerPage(request):
    return render(request, "admin/registerPage.html");


def register(request):
    userName = request.POST.get('userName');
    passWord = request.POST.get('password1');
    showName = request.POST.get('showName');
    try:
        userInfo(userName=userName,passWord=passWord,showName=showName).save();
    except Exception:
        return render(request,"error.html")
    user = userInfo.objects.filter(userName=userName);
    if user.count()>0:
        return render(request, "loginPage.html");
    else:
        return render(request,"error.html")



def projectCases(request):
    return render(request, "admin/projectCases.html");



def workerManagePage(request):
    users = userInfo.objects.all();
    context = {}
    context['users'] = users;
    return render(request,"admin/wokerManagePage.html",context);


@csrf_exempt
def workerManage(request):
    data = 1;
    status = request.POST.get('status');
    userId = request.POST.get('userId');
    try:
        user = userInfo.objects.get(id=userId);
        user.status = status;
        user.save();
    except Exception:
        data = 0;
    return HttpResponse(data);

def gotoCaseListPage(request):
    projectId = request.POST.get('projectId');
    stage = request.POST.get("stage");
    machine = request.POST.get("machine");
    casels = projectAndCaseRelations.objects.filter(projectId=projectId,status='1');
    context = {}
    project = projectInfo.objects.get(id=projectId);
    nb = notebookAndCellPhoneAndPadInfos.objects.get(id=int(machine));
    context['noteBook'] = nb;
    context['stage'] = stage;
    casesAndCaseDetailList = [];
    for casel in casels:
        caseAndCaseDetail = {};
        try:
            caseAndCaseDetail['case'] = caseInfo.objects.get(id=casel.caseId,status='1');
        except Exception:
            caseAndCaseDetail['case'] =[];
        try:
            caseAndCaseDetail['caseDetailList'] = caseDetail.objects.filter(caseTitleId=casel.caseId,status='1').order_by("-position");
        except Exception:
            caseAndCaseDetail['caseDetailList'] = [];
        casesAndCaseDetailList.append(caseAndCaseDetail);
    context['casesAndCaseDetailList'] = casesAndCaseDetailList;
    context['project'] = project;
    return render(request,'worker/goToCaseListPage.html',context);


def gotoCaseDetailContentPage(request):
    try:
        projectId = request.POST.get('projectId');
        caseTitleId = request.POST.get('caseTitleId');
        caseDetailId = request.POST.get('caseDetailId');
        stage = request.POST.get('stage');
        noteBookId = request.POST.get('noteBook');
        project = projectInfo.objects.get(id=projectId);
        caseTitle = caseInfo.objects.get(id=caseTitleId);
        aCaseDetail = caseDetail.objects.get(id=caseDetailId);
        noteBook = notebookAndCellPhoneAndPadInfos.objects.get(id=noteBookId);
        context = {}
        context['project'] = project;
        context['caseTitle'] = caseTitle;
        context['caseDetail'] = aCaseDetail;
        context['stage'] = 'SIT' if stage=='1' else 'SVT';
        context['noteBook'] = noteBook;
        userId = request.session.get('userId');
        bug = bugs.objects.filter(projectId=int(projectId), caseDetailId=int(caseDetailId),
                                  caseId=int(caseTitleId), userId=int(userId));
        if bug.count()>0:
            reason = '';
            if bug[0].comment is not None:
                reason = str.replace(bug[0].comment,'<br>','\n');
            bug[0].coomment = reason;
            imgIdInt = [];
            if bug[0].imgId is not None:
                imgIds = bug[0].imgId.split(',');
                if len(imgIds) > 0:
                    for id in imgIds:
                        imgIdInt.append(int(id))
            imgs = uploadImg.objects.filter(id__in=imgIdInt);
            context['imgs'] = imgs;
            context['reason'] = reason;
            context['title'] = bug[0].title
    except Exception:
        print(sys.exc_info())
    return render(request, 'worker/gotoCaseDetailContentPage.html', context);


def logout(request):
    result = 1;
    try:
        request.session.flush();
    except Exception:
        result = 0;
    return HttpResponse(result);
